/* *
 * 柱形图
 * 说明：能适应单指标、多指标的展示（考虑多指标时可以转变为堆叠图）
 *     data.datas = [
      {
        id: "aaa",
        name: "aaa",
        regioncode: "aaa",
        regionname: "aaa",
        maxdata: 10,
        mindata: 0,
        datas: {
          sdata: [
            {
              name: "直接访问",
              type: "bar",
              barWidth: "60%",
              data: [10, 52, 200, 334, 390, 330, 220]
            }
          ],
          xAxis: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
        },
        lon: "116.92866163503169",
        lat: "39.830660058696104"
      },
      {
        id: "bbb",
        name: "bbb",
        regioncode: "bbb",
        regionname: "bbb",
        datas: {
          sdata: [
            {
              name: "直接访问",
              type: "bar",
              barWidth: "60%",
              data: [10, 52, 200, 334, 390, 330, 220]
            }
          ],
          xAxis: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
        },
        lon: "104.04",
        lat: "30.40"
      }
    ]
 *
 */
import icon from "../../css/images/marker-icon.png";
import iconShadow from "../../css/images/marker-shadow.png";
import echarts from 'echarts'; // echarts 文件引入
import sgisLayerBase from '../../sfgis.layer.base';
import colorPicker from './echarts.colorpicker'; // 颜色初始化配置文件
import styleModify from './echarts.stylemodify'; // 样式修改，包括透明度设置，可见性，图层的ZIndex顺序设置文件
import store from "../../../../pages/macro/store";
import { getMapLayers } from "vuex";
import $ from 'jquery'
export default {
  activeMap: {}, // 当前活动地图
  barLayer: '',
  callback:"",
  barLayerInfo: {}, // 图层其他相关信息
  /**
   * 创建地柱形图专题图
   * @param {Object} map 地图对象
   * @param {Object} data 格式化好的数据
   *      {
   *        "id":"",  专题图的id
   *        "name":"",  专题图的名称
   *         showThumbnails:false,
   *        "datas":[{   数据
   *         "id":"",     每个点的echarts id
   *          "name":"",    每个点的echarts name
   *          "regioncode":"",    每个点对应的区划代码
   *          "regionname":"",     每个点对应的区划名称
   *          "datas":{"sdata":[],"xAxis":[]},   echarts对应的seris数据和x轴数据
   *          "lon":"",     坐标点Y
   *          "lat":"",     坐标点X
   *       },{}]
   *    }
   */
  createLayer(map, data, callback) {
    var compare = function(obj1, obj2) {
      var val1 = Number(obj1.regioncode);
      var val2 = Number(obj2.regioncode);
      if (val1 < val2) {
        return -1;
      } else if (val1 < val2) {
        return 1;
      } else {
        return 0;
      }
    };
    data.datas = data.datas.sort(compare);
    $(".bar_chart").remove();
    if (!data || data === undefined) {
      return;
    }
    if (!data.datas || data.datas === undefined) {
      return;
    }
    this.callback = callback;
    this.activeMap = map;
    const barMarkers = this.createMarker(data.datas, map); // 创建好所有marker
    // const DefaultIcon = L.icon({
    //   iconUrl: icon,
    //   shadowUrl: iconShadow
    // });
    // L.Marker.prototype.options.icon = DefaultIcon;
    const barLayer = barMarkers;
    styleModify.onZoom(this.activeMap, barMarkers); // 为markers绘图添加缩放监听改变z-Index;
    this.barLayer = barLayer;
    // 将容器加载到地图容器
    this.createCharts(barMarkers, data.datas);
    // 自定义颜色开始
    const id = "bar_chart_" + data.id + "_" + +new Date();
    // 设置容器初始ZINdex,为后面调整图层顺序功能 开始
    styleModify.setLayerOrder(styleModify.curZindex, barLayer, id);
    // 设置容器初始ZINdex,为后面调整图层顺序功能 结束
    styleModify.layerOrder[id] = styleModify.curZindex;
    styleModify.curZindex -= 1;
    // 设置容器初始ZINdex,为后面调整图层顺序功能 结束
    barLayer.setCustomColor = this.setCustomColor;
    barLayer.setOpacity = styleModify.setOpaticty; // 设置图层透明度
    barLayer.setVisible = styleModify.setVisible; // 设置图层可见性
    barLayer.setZIndexOffset = this.setZIndexOffset; // 设置调整图层顺序函数;
    barLayer.calSData = this.calSData
    barLayer.layerId = id;
    barLayer.calgraph = this.calgraph;
    // 自顶替颜色结束
    this.barLayerInfo = {
      name: data.name,
      type: "bar",
      layerId: "bar",
      show: data.showThumbnails !== false,
    };
    store.commit("getMapLayers", this.barLayerInfo)
    map.overlayers["bar"] = barLayer
    map.overlayerInfos["bar"] = this.barLayerInfo


    return this.barLayerInfo;
  },
  /**
   * 创建echarts容器
   * @param {Objects[]} datas
   */
  createMarker(datas, map) {
    const resultMarkers = [];
    for (let i = 0, len = datas.length; i < len; i++) {
      let time = +new Date();
      const data = datas[i];
      // 初始化最小宽高开始
      let width = colorPicker.size;
      if (data.hasOwnProperty('width')) {
        width = data.width.slice(0, -2);
        width = parseInt(width);
        if (width < colorPicker.size) {
          width = colorPicker.size;
        }
      }
      let height = colorPicker.size;
      if (data.hasOwnProperty('height')) {
        height = data.width.slice(0, -2);
        height = parseInt(height);
        if (height < colorPicker.size) {
          height = colorPicker.size;
        }
      }
      const iconWidth = width + 45;
      const iconHeight = height + 45;
      // 初始化最小宽高结束

      var el = document.createElement('div');
      el.className = `bar_chart chart_background`;
      el.id = "bar_chart_" + i + time;
      el.style.width = 60 + 'px';
      el.style.height = 60 + 'px';
      const chartMarker = new mapboxgl.Marker(el)
        .setLngLat([data.lon, data.lat])
        .addTo(map);
      resultMarkers.push(chartMarker);
    }


    return resultMarkers;
  },
  /**
   * 创建图表
   * @param {Object} barMarkers 图表容器
   * @param {Object} datas 数据
   */
  createCharts(barMarkers, datas) {
    const charts = [];
    if (!barMarkers || barMarkers === undefined) return;
    if (datas.length <= 5) {
      let i = 1;
      let optionTimer = setInterval(() => {

        let dataValue = datas.slice(0, i)
        this.getNewOptionList(dataValue,barMarkers)
        i++;
        if (i > datas.length) {
          this.barLayerInfo["html"] = this.calgraph("bar");
          
          sgisLayerBase.setOverLayers(this.barLayerInfo);
          this.barLayer.charts = [...this.charts];
          this.callback(this.barLayerInfo)
          clearInterval(optionTimer)
        }
      }, 500)

    }else{
      let i = 5;
      let optionTimer = setInterval(() => {
        let dataValue = datas.slice(0, i)
        this.getNewOptionList(dataValue,barMarkers)
        i+=5;
        if (i-datas.length > 5) {
          this.barLayerInfo["html"] = this.calgraph("bar");
          sgisLayerBase.setOverLayers(this.barLayerInfo);
          this.barLayer.charts = [...this.charts];
          this.callback(this.barLayerInfo)
          clearInterval(optionTimer)
        }
      }, 500)
    }


  },
  getNewOptionList(datas,barMarkers) {
    let charts = [];
    for (let i = 0; i < datas.length; i++) {
      const chartMarkerId = barMarkers[i]._element.id;
      if(!document.getElementById(chartMarkerId)){//找不到元素不再绘制
        return;
      }
      const chart = echarts.init(document.getElementById(chartMarkerId));
      const data = datas[i];
      this.graph = [];
      const chartOption = {
        title: {
          text: datas[i].name,
          textStyle:{
            fontWeight : 'normal',
            fontSize : '12px',
            color : '#5f5d5d'
          },
          bottom:'0',
          left: 'center',
        },
        idenCode: data.regioncode,
        color: store.state.macro.layerColors["bar"] ? store.state.macro.layerColors["bar"] : colorPicker.color,
        tooltip: {},
        grid: {
          left: "3%",
          right: "4%",
          bottom: "35%",
          top: "0",
          containLabel: true
        },
        xAxis: [{
          type: "category",
          data: data.datas.xAxis, // 设置x轴坐标
          axisLabel: {
            show: false
          },
          axisTick: {
            alignWithLabel: true
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: colorPicker.bar.axisColor
            }
          }
        }],
        yAxis: [{
          type: "value",
          max:data.maxdata,
          min:0,
          axisLabel: {
            show: false
          },
          splitLine: {
            show: false // 网格线不显示
          },
          axisLine: {
            show: false,
            lineStyle: {
              color: colorPicker.bar.axisColor
            }
          },
          axisTick:{
            show:false
          }
        }],
        series: this.calSData(data.datas.sdata, store.state.macro.layerColors["bar"] ? store.state.macro.layerColors["bar"] : colorPicker.color)
      };
      this.barLayer["option"] = chartOption
      chart.setOption(chartOption);
      charts.push({
        id: barMarkers[i]._element.id,
        echart: chart
      });
      /* *计算图例参数 */
      const colors = store.state.macro.layerColors["bar"] ? store.state.macro.layerColors["bar"] : colorPicker.color;
      
      data.datas.xAxis.map((item, index) => {
        let color = colors[index];
        this.graph.push({
          name: item,
          color
        });
      })
    }
    this.charts = charts;
  },
  /**
   *
   * @param {object} par{
     barStyle: [this.color1, "pink"],
     axisStyle: this.color1,
     axisLableStyle: this.color1
   }
   */
  setCustomColor(layers, pars) {

    const par = {
      ...pars,
      barStyle: pars.colors
    };
    for (let key in layers.charts) {
      let item = layers.charts[key];
      let option = item.echart.getOption();
      if (par.hasOwnProperty('barStyle')) {
        option.series = this.calSData(option.series, par.barStyle);
      }
      store.commit("layerColors", { type: "bar", color: par.barStyle })
      item.echart.clear();
      item.echart.setOption(option);
      let colors = item.echart.getOption().color;
      let datas = option.xAxis[0].data;
      this.graph = [];
      datas.map((name, index) => {
        let color = pars.colors[index];
        this.graph.push({
          name,
          color
        });
      })
      // 设置图例颜色 结束
    }
    layers.calgraph("bar", pars.colors);
  }, // 自定义柱状颜色时使用该函数
  /* *格式化数据
   * @params data 传入数据
   * @param {array} customColor
   */
  calSData(data, customColor) {
    for (const key in data) {
      let index, indexc;
      try {
        index = key % colorPicker.color.length;
        indexc = key % customColor.length;
      } catch (err) {
        index = 0;
        indexc = 0;
      }
      data[key] = {
        ...data[key],
        itemStyle: {
          normal: {
            color: function (params) {
              let colorList = customColor;
              return colorList[params.dataIndex];
            }
          }
        }
      };
    }
    return data;
  },
  /**
   * 格式化数据
   * @param {*} layerId 图层id
   */
  // 图例计算颜色 开始
  calgraph(layerId) {
    let html = `<div style="padding:6px" class="${layerId}">`;
    for (const key in this.graph) {
      html += `<div class='chart_item' style='display:flex;align-items: center;justify-content: flex-start;position: relative;'>
        <div style='display:inline-block;width:14px;height:4px;background:${this.graph[key].color};margin:0;padding:0;border-radius:4px;'>
        
        </div>
        <p>&nbsp;&nbsp;&nbsp;&nbsp;${this.graph[key].name}</p>
      </div>`;
    }
    html += '</div>';
    let layers = sgisLayerBase.overLayers;
    layers.map(item => {
      if (item.type == layerId) {
        item.html = html
      }
    })
    return html;
  },
  /**
   *格式化数据
   * @param {*} layerId 图层id
   */
  autoCalgraph(layerId) {
    let html = `<div style="padding:6px" id="${layerId}">`;
    for (const key in this.graph) {
      
      html += `<div class='chart_item' style='display:flex;align-items: center;justify-content: flex-start;position: relative;'>
      <div style='display:inline-block;width:14px;height:4px;background:${this.graph[key].color};margin:0;padding:0;border-radius:4px;'>
      
      </div>
      <p>&nbsp;&nbsp;&nbsp;&nbsp;${this.graph[key].name}</p>
    </div>`;
    }
    html += '</div>';
    const layers = sgisLayerBase.overLayers;
    for (const key in layers) {
      if (layers[key].layerId === layerId) {
        layers[key].html = html;
      }
    }
    // sgisLayerBase.layerControlChange();
  },
  // 图例计算颜色 结束
  /** 设置调整图层顺序函数*/
  setZIndexOffset(index) {
    styleModify.setZIndexOffset(index, this.layerId, this._layers);
  }
};
